package com.ktjy;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class SimpleQueueProducer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //建立连接
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/T384");
        //创建连接对象
        Connection connection = factory.newConnection();
        //创建信道对象
        Channel channel = connection.createChannel();

        //定义一个队列
        String queueName="simple_queue";
        channel.queueDeclare(queueName,true,false,false,null);

        //发信息
        String msg="hello world";

        AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                .deliveryMode(2) // 关键：设置为 2 表示消息持久化
                .build();

        channel.basicPublish("",queueName,properties,msg.getBytes());

        System.out.println("消息发送成功");

        //关闭信道和连接对象
        channel.close();
        connection.close();
    }
}
